package com.bruce.pattern.creational.singleton;

import org.springframework.util.StringUtils;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单例容器
 * <p>
 * Created by bruce on 2018/11/3 13:51
 */
public class ContainerSingletion {
    private static ConcurrentHashMap<String, Object> singletionMap = new ConcurrentHashMap<>();

    private ContainerSingletion() {

    }

    //明显这个方法不是线程安全的
    // public static void putInstance(String key, Object obj) {
    //     if (!singletionMap.containsKey(key)) {
    //         singletionMap.put(key, obj);
    //     }
    // }

    //线程安全
    public static boolean putInstance(String key, Object obj) {
        if (StringUtils.hasText(key) && Objects.nonNull(obj)) {
            return singletionMap.putIfAbsent(key, obj) == null;
        }
        return false;
    }

    public static Object getInstance(String key) {
        return StringUtils.hasText(key) ? singletionMap.get(key) : null;
    }


}
